import store from "@/store";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import axios from "axios";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: () => import("../views/HomeIndex.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginIndex.vue"),
    meta: { redirectAlreadyLogin: true },
  },
  {
    path: "/register",
    name: "register",
    component: () => import("../views/SignUp.vue"),
    meta: { redirectAlreadyLogin: true },
  },
  {
    path: "/colmun/:id",
    name: "colmun",
    component: () => import("../views/ColmunDetail.vue"),
    meta: { requiredLogin: true }
  },
  {
    path: "/create",
    name: "create",
    component: () => import("../components/CreatePost.vue"),
    meta: { requiredLogin: true }
  },
  {
    path: "/wenzhang/:id",
    name: "wenzhang",
    component: () => import("../views/PostDetail.vue")
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const { user, token } = store.state;
  const { redirectAlreadyLogin, requiredLogin } = to.meta;
  if (!user.isLogin) {
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      store
        .dispatch("fetchCurrentUser")
        .then(() => {
          if (redirectAlreadyLogin) {
            next("/");
          } else {
            next();
          }
        })
        .catch((e) => {
          // localStorage.removeItem("token");
          store.commit('logout')
          next("/login");
        });
    } else {
      if (requiredLogin) {
        next("/login");
      } else {
        next();
      }
    }
  } else if (redirectAlreadyLogin) {
    next("/");
  } else {
    next();
  }
});

export default router;
